let handle = document.getElementById('handle')
let stop = document.getElementById('stop')
// let log = document.getElementById('log-area')
let bg = chrome.extension.getBackgroundPage()

handle.addEventListener('click', (event) => {
  const inputDom = document.getElementsByTagName('input')
  var setting = {
    hour: '15',
    min: '15',
    sec: '15'
  }
  let errArr = []
  if (inputDom[0].value < 0 || inputDom[0].value > 23 || inputDom[0].value === '') {
    errArr.push('【时】输入范围为0-23')
  }
  if (inputDom[1].value < 0 || inputDom[1].value > 60 || inputDom[1].value === '') {
    errArr.push('【分】输入范围为0-60')
  }
  if (inputDom[2].value < 0 || inputDom[2].value > 60 || inputDom[2].value === '') {
    errArr.push('【秒】输入范围为0-60')
  }
  const errDom = document.getElementsByClassName('err-msg')[0]
  if (errArr.length > 0) {
    errDom.innerHTML = errArr.join('、') + '且均不能为空'
    errDom.style.display = 'block'
    return
  } else {
    errArr = []
    errDom.style.display = 'none'
  }
  setting.hour = inputDom[0].value || setting.hour
  setting.min = inputDom[1].value || setting.min
  setting.sec = inputDom[2].value || setting.sec

  for (let key in setting) {
    if (setting[key].length === 1) {
      setting[key] = '0' + setting[key]
    }
  }

  console.log(setting)

  chrome.tabs.query({
    active: true,
    currentWindow: true,
  }, (tabs) => {
    chrome.scripting.executeScript({
      args: [setting],
      target: { tabId: tabs[0].id },
      func: (setting) => {
        compareTime(setting)
      }
    })
  })
})

stop.addEventListener('click', (event) => {
  chrome.tabs.query({
    active: true,
    currentWindow: true,
  }, (tabs) => {
    chrome.scripting.executeScript({
      args: [],
      target: { tabId: tabs[0].id },
      func: () => {
        if (intervalID) {
          clearInterval(intervalID)
          console.log('任务停止')
        } else {
          Toast('没有在执行的任务')
        }
      }
    })
  })
  $('#place').before('<li style="color: red;">任务被手动停止</li>')
  gotoBottom()
})

chrome.runtime.onMessage.addListener((msg, sender, response) => {
  console.log(msg)
  if (msg.index === 0) {
    $('#place').before('<li style="color: green;">执行完成</li>')
  }
  else if (msg.index === 1) {
    $('#place').before('<li>正在进行时钟比对...</li>')
  }
  // gotoBottom()
})

function gotoBottom() {
  let scrollHeight = $('#log-ul').prop('scrollHeight')
  if (scrollHeight > $('#log-ul').prop('clientHeight')) {
    $('#log-ul').scrollTop(scrollHeight, 200)
  }
}

